package com.dream.wukong.common.core.importexport.csv.impl;

import com.dream.wukong.common.core.importexport.csv.CsvExport;
import com.dream.wukong.common.core.importexport.csv.config.CsvTable;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: wuyichao
 * @Description:
 * @Date: Created in 16:25 2018/9/17.
 * @Modified:
 */
@Component("csvExport")
public class CsvExportImpl extends BaseCsvOperations implements CsvExport {

    @Override
    public void expToFile(List<? extends Object> rows, String tableId, File destFile, List<? extends CsvTable.CsvField> fields) {
        List<Object[]> records = new ArrayList<Object[]>();
        //1.添加标题行
        if (getHeaderEnabled(tableId)) {
            List<Object> header = new ArrayList<Object>();
            for (CsvTable.CsvField csvField : fields) {
                String colInfo =csvField.getDesc();
                header.add(colInfo );
            }
            records.add(header.toArray());
        }

        //2.添加数据行
        if(rows!=null) {
            for (Object data :rows) {
                records.add(getRow(data, fields));
            }
        }
        //销毁convert列值转化对象
        removeConvertThreadLocal();
        //3.写入到文件
        getParser().writeRows(records, destFile.getAbsolutePath());
    }


    @Override
    public void expToFile(List<? extends Object> rows, String tableId, File destFile, List<? extends CsvTable.CsvField> oldfields, List<Integer> options) {
        List<Object[]> records = new ArrayList<Object[]>();

        //0.根据用户选择输出指定列
        List<CsvTable.CsvField> fields = new ArrayList<CsvTable.CsvField> ();
        for (int i = 0; options!=null&&i < options.size(); i++) {
            int idx = Integer.valueOf(options.get(i));
            fields.add(oldfields.get(idx)) ;
        }

        //1.添加标题行
        if (getHeaderEnabled(tableId)) {
            List<Object> header = new ArrayList<Object>();
            for (CsvTable.CsvField csvField : fields) {
                header.add(csvField.getDesc());
            }
            records.add(header.toArray());
        }

        for (Object data :rows) {
            records.add(getRow(data, fields));
        }

        //销毁convert列值转化对象
        removeConvertThreadLocal();
        //3.写入到文件
        getParser().writeRows(records, destFile.getAbsolutePath());
    }
}
